import app from '@/app'
import { get, update, del } from '@/api/erp/pay'

import base from '@/app/model'

// 继承总模型
const model = new base;

model.get = () => {
  return new Promise((resolve, jeject) => {
    get().then(res => {
      model.setList(res)
      resolve(res)
    }).catch(res => {
      jeject(res)
    })
  })
}

model.update = (...arge) => {
  return new Promise((resolve, jeject) => {
    update(...arge).then(res => {
      model.get()
      app.ui.message('success', res.message)
      resolve(res)
    }).catch(res => {
      app.ui.message('error', 'error.' + res.message)
      jeject(res)
    })
  })
}

model.del = (...arge) => {
  return new Promise((resolve, jeject) => {
    del(...arge).then(res => {
      model.get()
      app.ui.message('success', res.message)
      resolve(res)
    }).catch(res => {
      app.ui.message('error', 'error.' + res.message)
      jeject(res)
    })
  })
}

// 循环创建默认方式
model.default = list => {
  list.forEach(item => {
    update(item).then(() => {
      model.get()
    })
  })
}

// 获取可使用的支付方式
model.getAll = (money = 0) => {
  // 限额检测
  const norm = (a, b) => {
    a = Number(a)
    b = Number(b)
    if(a > 0 && b > 0) {
      return a > b
    }
    return true
  }
  return model.getList().filter(item => item.status && norm(item.norm, money))
}

// 获取默认支付方式
model.getDefault = () => {
  return model.getList()[0] ?? {}
}

model.id = id => {
  return model.getList().find(item => item.id == id)
}

// 获取支付方式名称
model.name = id => {
  const pay = model.id(id)
  return pay ? pay.name : ''
}

// 获取支付方式需要打开钱箱
model.cashbox = id => {
  const pay = model.id(id)
  return pay ? pay.cashbox : 0
}

export default model